
layui.use(['jquery', 'laytpl', 'laypage'],function () {
    var $ = layui.jquery,
        laypage = layui.laypage,
        laytpl = layui.laytpl;


    var count;     //每次获取的商品数
    var limit = 10;     //每页显示条目数
    var curPageGoods = {};
    var goods;


    $(function loadMyGoods() {

        //分页选择页数 监听
        $('.sel').on("change",onChoosePage());
        $.ajax({
            url: "goods.json",
            async: true,
            dataType: "json",
            success: function (data) {
                goods = data;
                count = goods.count;
                renderPages(goods.count);//分页
                $('#sz_page_box').css("margin", "0 auto");
            }
        });
    });


//分页选择页数 监听
    function onChoosePage() {
        paging(goods, 1);
        renderGoods(curPageGoods);
    }

//处理页数与商品映射
    function paging(goods, pageNum) {
        pageNum = parseInt(pageNum);
        var singletonPageGoods = [];
        var start = (pageNum - 1) * limit;
        var end = (start + limit) > count ? count : start + limit;
        for (var i = start; i < end; i++) {
            singletonPageGoods[i - start] = JSON.stringify(goods.list[i]);
        }
        curPageGoods.list = JSON.parse('[' + singletonPageGoods.toString() + ']');
    }

//异步渲染数据
    function renderGoods(data) {
        var getTpl = goodBoxTpl.innerHTML
            , view = document.getElementById('goods-list');
        laytpl(getTpl).render(data, function (html) {
            view.innerHTML = html;
        });
    }

//分页
    function renderPages(count) {
        $('#all_number_sz').text(count);
        laypage.render({
            elem: 'sz_page_box',
            limit: limit,
            layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
            groups: 4,
            count: count, //从服务端取得,
            jump: function (obj, first) {
                limit = obj.limit;
                paging(goods, 1);
                if (!first) {
                    paging(goods, obj.curr);
                }
                renderGoods(curPageGoods);
            }
        });
    }

});

